#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

// key_t ftok(const char *pathname, int proj_id);

struct msgbuf
{
    long mtype;       // 数据的编号
    char mtext[1024]; // 数据的正文
};

void *start_routine(void *arg)
{
    key_t key = ftok("./", 200);
    int msgid = msgget(key, IPC_CREAT | 0666);

    struct msgbuf data;
    memset(&data, 0, sizeof(data));

    while (1)
    {
        int ret = msgrcv(msgid, &data, sizeof(data.mtext), 10, 0);
        // printf("msgrcv ret :%d data:%s\n", ret, data.mtext);
        printf("新消息：%s", data.mtext);

        if (ret == -1)
        {
            perror("msgrcv");
        }
    }
}

int main()
{
    pthread_t thread;
    int res = pthread_create(&thread, NULL, start_routine, NULL);

    key_t key = ftok("./", 100);
    int msgid = msgget(key, IPC_CREAT | 0666);

    // 创建消息结构体
    struct msgbuf data;
    memset(&data, 0, sizeof(data));
    data.mtype = 100;

    while (1)
    {
        // printf("请输入要发送的数据：\n");
        fgets(data.mtext, sizeof(data.mtext), stdin);

        if (strcmp(data.mtext, "exit\n") == 0)
        {
            pthread_cancel(thread);
            return 0;
        } // 往消息队列中 发送数据
        msgsnd(msgid, &data, sizeof(data.mtext), 0);
    }

    return 0;
}
